var express = require('express')
var fs = require('fs')
var path = require('path')

var router = express.Router()

var datafile = path.join(__dirname, '../api/prodlist.json')


router.get('/api/getprodlist', function (req, res) {
    fs.readFile(datafile, 'utf8', function (err, data) {
        if (err) {
            return res.send('readFile error')
        }
        var status = 0
        var message = JSON.parse(data).message
        var content = JSON.stringify({
                status: status,
                message: message
            })
            // console.log(JSON.parse(content))
        res.send(content)
    })

})
router.post('/api/addproduct', function (req, res) {
    var body = req.body

    fs.readFile(datafile, 'utf8', function (err, data) {
        if (err) {
            return res.send('readFile error')
        }
        var dataObj = JSON.parse(data)
        var message = dataObj.message
        var maxNum = dataObj.maxNum
        message.push({
            id: ++maxNum,
            name: body.name,
            ctime: new Date().toString()
        })
        var content = JSON.stringify({
            maxNum: maxNum,
            message: message
        })
        console.log(content)
        fs.writeFile(datafile, content, 'utf8', error => {
            if (error) {
                console.log(error)
            }
            var status = 0
            var content = JSON.stringify({
                status: status,
                message: message
            })
            res.send(content)
        })
    })
})
router.get('/api/delproduct', function (req, res) {
    var id = req.query.id
    console.log(id)
    fs.readFile(datafile, 'utf8', function (err, data) {
        if (err) {
            return res.send('readFile error')
        }
        var dataObj = JSON.parse(data)
        var message = dataObj.message
        var maxNum = dataObj.maxNum
        var index = message.findIndex(function (item) {
            if (item.id == id) {
                return true
            }
        })
        console.log(index)
        message.splice(index, 1)
        var content = JSON.stringify({
            maxNum: maxNum,
            message: message
        })
        console.log(content)
        fs.writeFile(datafile, content, 'utf8', error => {
            if (error) {
                console.log(error)
            }
            var status = 0
            var content = JSON.stringify({
                status: status,
                message: message
            })
            res.send(content)
        })

    })
})


module.exports = router